package com.gitee.linmt.controller;

import com.gitee.linmt.entity.UserInfo;
import com.gitee.linmt.service.UserInfoService;
import com.gitee.linmt.util.PasswordUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author linmt
 */
@RestController
public class Controller {

    private final UserInfoService userInfoService;

    public Controller(UserInfoService userInfoService) {
        this.userInfoService = userInfoService;
    }

    /**
     * 自定义用户登录认证
     *
     * @param userInfo 用户信息
     * @return 用户信息
     */
    @PostMapping("/login")
    public UserInfo login(@RequestBody UserInfo userInfo) {
        Subject currentUser = SecurityUtils.getSubject();
        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken();
            usernamePasswordToken.setUsername(userInfo.getUsername());
            usernamePasswordToken.setPassword(userInfo.getPassword().toCharArray());
            currentUser.login(usernamePasswordToken);
        }
        return userInfoService.findByUsername(userInfo.getUsername());
    }

    /**
     * 无权限时，结合全局异常处理，自定义返回信息
     *
     * @return 返回信息
     */
    @RequestMapping("/unauthorized")
    public String unauthorized() {
        return "没有权限";
    }

    /**
     * 注册用户
     *
     * @param userInfo 用户信息
     * @return 注册后的用户信息
     */
    @PostMapping("/registered")
    public UserInfo registered(@RequestBody UserInfo userInfo) {
        PasswordUtil.setSaltAndEncodedPassword(userInfo);
        userInfoService.save(userInfo);
        return userInfo;
    }
}
